<!-- eslint-disable no-mixed-spaces-and-tabs -->
<template>
    <div class="mcTableIndex">
        <div class="mcTableList">
            <el-table
                :data="tableData"
                border
                style="width: 100%"
                ref="table"
                :height="curHeight ? curHeight : 'calc(100vh - 200px)'"
                highlight-current-row
                @row-click="handleClickTableRow"
                @selection-change="handleSelectionChange"
                @current-change="handleCurrentChange"
                :row-style="rowClass"
                :cell-style="{padding: '0'}"
            >
                <!-- 是否开启选择框 begin -->
                <el-table-column type="selection" width="40" v-if="hasSelect"> </el-table-column>
                <!-- 是否开启选择框 end -->
                <!-- 字段列展示 begin -->
                <el-table-column label="序号" align="center" width="60" fixed>
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <!-- 列头只有一行，没有合并的情况 -->

                <!-- 列头有合并的情况 -->
                <el-table-column
                    :prop="item.prop"
                    :label="item.label"
                    :width="item.width ? item.width : 'auto'"
                    :align="item.align ? item.align : 'center'"
                    v-for="(item, index) in tableColumn"
                    :key="index"
                >
                    <template slot-scope="scope">
                        <slot :name="scope.row[item.prop]" :params="scope.row">
                            <div v-if="item.prop == 'xxjsfs'">
                                <p style="text-align: left">
                                    <el-checkbox disabled v-model="scope.row.webInfo">Web系统消息</el-checkbox>
                                </p>
                                <p style="text-align: left">
                                    <el-checkbox disabled v-model="scope.row.appInfo">App系统消息</el-checkbox>
                                </p>
                                <p style="text-align: left">
                                    <el-checkbox disabled v-model="scope.row.emailInfo">邮件通知</el-checkbox>
                                </p>
                                <p style="text-align: left">
                                    <el-checkbox disabled v-model="scope.row.telInfo">手机短信通知</el-checkbox>
                                </p>
                            </div>
                            <div v-else-if="item.prop == 'roleConfig'">
                                <el-button type="primary" size="mini" @click="roleMenu(scope.row)">
                                    <i class="el-icon-menu"></i> 菜单
                                </el-button>
                                <el-button type="primary" size="mini" @click="roleUser(scope.row)">
                                    <i class="el-icon-user"></i> 用户
                                </el-button>
                            </div>
                            <div v-else-if="item.prop == 'oprType'">
                                <el-button type="info" plain size="small">{{ getDictValue('oprType', scope.row.oprType) }}</el-button>
                            </div>
                            <div v-else-if="item.prop == 'serviceStatus'">
                                <label v-if="scope.row.serviceStatus == '1'" class="greenserviceStatus"> 服务正在运行 </label>
                                <label v-if="scope.row.serviceStatus == '2'" class="redserviceStatus"> 服务已停止 </label>
                            </div>

                            <div v-else>
                                <el-tooltip
                                    class="item"
                                    effect="dark"
                                    :content="
                                        changeToString(
                                            item.dictName ? getDictValue(item.dictName, scope.row[item.prop]) : scope.row[item.prop]
                                        )
                                    "
                                    placement="top"
                                >
                                    <label
                                        :class="item.class ? getClassName(item.class, scope.row[item.prop]) : ''"
                                        :style="
                                            item.style
                                                ? item.style
                                                : {
                                                      fontWeight: getCheckValue(scope.row, item.prop, 'fontWeight'),
                                                      color: getCheckValue(scope.row, item.prop, 'color'),
                                                      textOverflow: 'ellipsis',
                                                      whiteSpace: 'nowrap',
                                                      overflow: 'hidden'
                                                  }
                                        "
                                    >
                                        {{ item.dictName ? getDictValue(item.dictName, scope.row[item.prop]) : scope.row[item.prop] }}
                                    </label>
                                </el-tooltip>
                            </div>
                        </slot>
                    </template>
                    <div v-if="item.children && item.children.length > 0">
                        <el-table-column
                            :prop="child.prop"
                            :label="child.label"
                            :width="child.width ? child.width : 'auto'"
                            :align="child.align ? child.align : 'center'"
                            v-for="(child, cIndex) in item.children"
                            :key="cIndex"
                        >
                            <template slot-scope="scope">
                                <slot :name="scope.row[child.prop]" :params="scope.row">
                                    <el-tooltip
                                        class="item"
                                        effect="dark"
                                        :content="
                                            changeToString(
                                                child.dictName ? getDictValue(child.dictName, scope.row[child.prop]) : scope.row[child.prop]
                                            )
                                        "
                                        placement="top"
                                    >
                                        <label
                                            :style="{
                                                fontWeight: getCheckValue(scope.row, child.prop, 'fontWeight'),
                                                color: getCheckValue(scope.row, child.prop, 'color'),
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden'
                                            }"
                                        >
                                            {{
                                                child.dictName ? getDictValue(child.dictName, scope.row[child.prop]) : scope.row[child.prop]
                                            }}
                                        </label>
                                    </el-tooltip>
                                </slot>
                            </template>
                        </el-table-column>
                    </div>
                </el-table-column>
                <!-- 字段列展示 end -->

                <!-- 操作按钮集合 begin -->
                <el-table-column
                    v-if="tableBtn && tableBtn.length > 0"
                    fixed="right"
                    label="操作"
                    :width="btnListWidth ?? tableBtn.length * 45"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="tableBtn.includes('resetXf')"
                            @click.native.prevent="xfRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            重新下发
                        </el-button>
                        <el-button
                            v-if="retestShow(scope.$index, tableData)"
                            @click.native.prevent="retestRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            复测
                        </el-button>
                        <el-button
                            v-if="tableBtn.includes('edit')"
                            @click.native.prevent="editRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            编辑
                        </el-button>
                        <el-button
                            v-if="tableBtn.includes('view')"
                            @click.native.prevent="viewRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            详情
                        </el-button>
                        <el-button
                            v-if="tableBtn.includes('lookSMJ')"
                            @click.native.prevent="lookSMJRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            预览
                        </el-button>
                        <el-button
                            v-if="tableBtn.includes('delete')"
                            @click.native.prevent="deleteRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                            style="color: red"
                        >
                            删除
                        </el-button>
                        <el-button
                            v-if="tableBtn.includes('edc')"
                            @click.native.prevent="edcRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            edc导出
                        </el-button>
                        <el-button
                            v-if="tableBtn.includes('download')"
                            @click.native.prevent="downloadRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            下载
                        </el-button>

                        <el-button
                            v-if="tableBtn.includes('isSc')"
                            @click.native.prevent="scRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            {{ tableData[scope.$index].isSc == 1 ? '取消收藏' : '收藏' }}
                        </el-button>

                        <el-button
                            v-if="tableBtn.includes('serviceStatus')"
                            @click.native.prevent="scRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            {{ tableData[scope.$index].serviceStatus == 1 ? '停止' : '启动' }}
                        </el-button>

                        <el-button
                            v-if="tableBtn.includes('resetPwd')"
                            @click.native.prevent="resetPwdRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            重置密码
                        </el-button>

                        <el-button
                            v-if="tableBtn.includes('relationUser')"
                            @click.native.prevent="relationUserRow(scope.$index, tableData)"
                            type="text"
                            size="small"
                        >
                            关联用户
                        </el-button>
                    </template>
                </el-table-column>
                <!-- 操作按钮集合 end -->
            </el-table>
        </div>
        <div class="mcCommonPager" v-if="tableData && tableData.length > 0">
            <el-pagination
                background
                :layout="hasIsSizes ? 'prev, pager, next,total,sizes' : 'prev, pager, next,total'"
                :total="count"
                :page-size="size"
                :current-page="current"
                @current-change="pageChange"
                :page-sizes="[20, 100, 500, 1000, 5000]"
                @size-change="handleSizeChange"
            >
                >
            </el-pagination>
        </div>

        <el-dialog
            title="温馨提示"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="closeDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <span style="padding-bottom: 10px; display: block">请输入删除原因：</span>
            <el-input type="textarea" v-model="optReason"></el-input>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="handleClose">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'

// pageNo 当前第几页
// pageSize 每页条数

export default {
    props: {
        /** 数据源：这里不确定字段，只要是数组就可以 */
        dataSource: {
            /** 这里不确定字段，只要是数组就可以 */
            type: Array,
            required: true
        },
        /** 自定义列 */
        tableColumns: {
            /** 格式： [{prop:"",label:"",width:"",children:[{prop:"",label:"",width:""]}] 其中宽度可以不写，目前只支持列头合并两行的情况，暂未做动态循环配置。 */
            type: Array,
            required: true
        },
        /** 操作按钮集合 */
        btnList: {
            /** 格式：['edit','view','delete','lookSMJ'] ，可以给空 */
            type: Array
        },
        btnListWidth: {
            type: String,
            require: false
        },
        /** 一页显示多少条数据 */
        pageSize: {
            type: Number,
            require: true
        },
        /** 总共有多少条数据 */
        pageCount: {
            type: Number,
            require
        },
        /** 当前第几页 */
        pageNo: {
            type: Number,
            require
        },
        /** 是否开启勾选框 */
        selection: {
            type: Boolean
        },
        /** 是否展示一页显示多少条数据*/
        isSizes: {
            type: Boolean
        },
        height: {
            type: String
        }
    },
    computed: {
        tableData() {
            return this.dataSource
        },
        tableColumn() {
            return this.tableColumns
        },
        tableBtn() {
            return this.btnList
        },
        size() {
            return this.pageSize
        },
        count() {
            return this.pageCount
        },
        current() {
            return this.pageNo
        },
        hasSelect() {
            return this.selection
        },
        hasIsSizes() {
            return this.isSizes
        },
        curHeight() {
            return this.height
        }
    },
    data() {
        return {
            multipleSelection: [],
            dialogVisible: false,
            formData: {},
            optReason: '',
            currentRow: null
        }
    },
    methods: {
        roleMenu(item) {
            this.$emit('roleMenu', item)
        },
        roleUser(item) {
            this.$emit('roleUser', item)
        },
        handleCurrentChange(val) {
            this.currentRow = val
            this.$emit('handleCurrentChange', val)
        },
        getClassName(name, value) {
            if (name == 'elementStatus') {
                if (value == '1') {
                    return 'elementFBZ'
                }
                if (value == '2') {
                    return 'elementYFB'
                }
                if (value == '3') {
                    return 'elementDFB'
                }
            }
            return name
        },
        retestShow(i, d) {
            return this.tableBtn.includes('retest') && !d[i].retestId
        },
        // 点击行勾选数据
        handleClickTableRow(row) {
            this.$refs.table.toggleRowSelection(row)
        },
        rowClass(row) {
            if (row.row.retestId) {
                return {
                    height: '40px',
                    'background-color': '#B0CAE5'
                }
            } else {
                return {
                    height: '40px'
                }
            }
        },
        // 将tooltip的值转成string类型，数字类型vue报js错误，虽然实际不影响。
        changeToString(value) {
            if (value) {
                return value.toString()
            } else {
                return ''
            }
        },
        handleSizeChange(e) {
            this.$emit('handleSizeChange', e)
        },
        getCheckValue(row, curColumnName, style) {
            let newValue = ''
            if (style == 'fontWeight') {
                newValue = 'normal'
            } else {
                newValue = '#606266'
            }
            if (row.autoCheckResult) {
                const autoCheckResult = JSON.parse(row.autoCheckResult)
                if (typeof autoCheckResult[curColumnName] != 'undefined' && autoCheckResult[curColumnName] == false) {
                    if (style == 'fontWeight') {
                        newValue = 'bold'
                    } else {
                        newValue = 'red'
                    }
                }
            }
            return newValue
        },
        getDictValue(dictType, dictValue) {
            let finishValue = dictValue
            const list = Utility.getDictList(dictType)
            if (list && list.length > 0 && typeof dictValue != 'undefined' && dictValue != null) {
                dictValue = dictValue.toString()
                if (dictValue.indexOf(',') != -1) {
                    dictValue = dictValue.split(',')
                    finishValue = list
                        .filter((t) => dictValue.includes(t.value))
                        .map((t) => t.label)
                        .join(',')
                } else {
                    const item = list.find((t) => t.value == dictValue)
                    if (typeof item != 'undefined') {
                        finishValue = item.label
                    }
                }
            }
            return finishValue
        },
        editRow(i, d) {
            const data = {
                index: i,
                data: d[i]
            }
            data.data.id = data.data.id ? data.data.id : data.data.oldId
            this.$emit('editRow', data)
        },
        xfRow(i, d) {
            const data = {
                index: i,
                data: d[i]
            }
            data.data.id = data.data.id ? data.data.id : data.data.oldId
            this.$emit('editRow', data)
        },
        retestRow(i, d) {
            const data = {
                index: i,
                retestId: d[i].oldId ? d[i].oldId : d[i].id,
                data: d[i]
            }
            data.data.oldId = data.data.oldId ? data.data.oldId : data.data.id
            data.data.id = null
            this.$emit('retestRow', data)
        },
        viewRow(i, d) {
            const data = {
                index: i,
                data: d[i]
            }
            this.$emit('viewRow', data)
        },
        lookSMJRow(i, d) {
            const data = {
                index: i,
                data: d[i]
            }
            this.$emit('lookSMJRow', data)
        },
        closeDialog() {
            this.dialogVisible = false
        },
        handleClose() {
            if (this.optReason == '') {
                PopupCommon.notify('info', '请填写删除原因')
                return
            }
            let data = this.formData
            data.optReason = this.optReason
            this.$emit('deleteRow', data)
            this.dialogVisible = false
        },
        deleteRow(i, d) {
            let self = this
            PopupCommon.confirm('此操作将删除该数据, 是否继续?')
                .then(() => {
                    // self.optReason = ""
                    // self.dialogVisible = true
                    // optReason
                    const data = {
                        index: i,
                        data: d[i]
                    }
                    self.formData = data
                    this.$emit('deleteRow', data)
                })
                .catch(() => {
                    // 这里尽量写下，否则会报警告异常。
                    console.log('已取消删除')
                })
        },
        edcRow(i, d) {
            let self = this
            PopupCommon.confirm('是否导出EDC')
                .then(() => {
                    // optReason
                    const data = {
                        index: i,
                        data: d[i]
                    }
                    self.formData = data
                    this.$emit('edcRow', data)
                })
                .catch(() => {
                    // 这里尽量写下，否则会报警告异常。
                    console.log('已取消导出EDC')
                })
        },
        resetPwdRow(i, d) {
            const data = {
                index: i,
                data: d[i]
            }
            self.formData = data
            this.$emit('resetPwdRow', data)
        },
        relationUserRow(i, d) {
            const data = {
                index: i,
                data: d[i]
            }
            self.formData = data
            this.$emit('relationUserRow', data)
        },
        scRow(i, d) {
            var str = ''
            if (d[i].isSc == 1) {
                str = '是否取消收藏？'
            } else {
                str = '是否收藏？'
            }
            let self = this
            PopupCommon.confirm(str)
                .then(() => {
                    if (d[i].isSc == 1) {
                        d[i].isSc == 0
                    } else {
                        d[i].isSc == 1
                    }
                    const data = {
                        index: i,
                        data: d[i]
                    }
                    self.formData = data
                    // this.$emit("scRow", data)
                })
                .catch(() => {
                    // 这里尽量写下，否则会报警告异常。
                    console.log('已取消收藏')
                })
        },
        downloadRow(i, d) {
            console.log(i, d)
        },
        // 页码点击事件,p当前页
        pageChange(p) {
            this.$emit('pageChange', p)
        },
        /** 改变选中行的值 */
        handleSelectionChange(val) {
            this.multipleSelection = val
            // this.$emit("handleSelectionChange", val)
        }
    },
    mounted() {
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'))
        }, 5000)
    },
    destroyed() {
        this.optReason = ''
        this.formData = {}
    }
}
</script>

<style scoped>
.mcTableIndex {
    margin-top: 10px;
    height: calc(100vh - 135px);
}

.mcTableIndex .mcTableList {
    /* 避免出现滚动条 */
    max-height: calc(100% - 35px);
    overflow: hidden;
}

.mcTableIndex .mcCommonPager {
    margin-top: 10px;
    background-color: #fff;
    padding: 5px 0;
    text-align: right;
}
.greenserviceStatus {
    color: green;
}
.redserviceStatus {
    color: red;
}
</style>
